package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Visitors;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

;import java.util.List;

@DubboService
public class VisitorsApiImpl implements VisitorsApi{

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存访问好友记录
     * @param visitors
     */
    @Override
    public void save(Visitors visitors) {
        //1.构造条件查询记录是否存在
        Query query = Query.query(Criteria.where("userId").is(visitors.getUserId())
                .and("visitDate").is(visitors.getVisitDate())
                .and("visitorUserId").is(visitors.getVisitorUserId()));
        //2.判断是否存在
        boolean exists = mongoTemplate.exists(query,Visitors.class);
        if (! exists) {
            //3.不存在就保存
            mongoTemplate.save(visitors);
        }
    }

    /**
     * 谁看过我
     * @param date
     * @param userId
     * @return
     */
    @Override
    public List<Visitors> queryVisitorsList(Long date, Long userId) {
        //1.创建条件
        Criteria criteria = Criteria.where("userId").is(userId);

        //如果时间不等于空，查询来访时间最新的几条数据
        if (date != null) {
            criteria.and("date").gt(date);
        }
        Query query = Query.query(criteria);
        //2.放回Visitors对象数据
        return mongoTemplate.find(query, Visitors.class);
    }
}
